<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      label-width="auto"
      class="ry_form">
      <el-form-item label="订单类型" prop="orderType">
        <el-select v-model="queryParams.orderType" clearable size="small">
          <el-option
            v-for="item in orderTypeMap"
            :key="item.value"
            :label="item.label"
            :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="下单时间" prop="Time">
        <el-date-picker
          v-model="queryParams.Time"
          type="datetimerange"
          :picker-options="pickerOptions"
          range-separator="至"
          size="small"
          format="yyyy-MM-dd HH:mm:ss"
          value-format="yyyy-MM-dd HH:mm:ss"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="['00:00:00', '23:59:59']"
          align="right"
          @change="handleChange">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="订单状态" prop="status">
        <el-select v-model="queryParams.orderStatus" clearable size="small">
          <el-option
            v-for="item in orderStatusMap"
            :key="item.value"
            :label="item.label"
            :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item
        label="下单手机号"
        prop="userPhone">
        <el-input
          size="small"
          v-model.trim="queryParams.orderPhone"
          placeholder="请输入下单手机号"
          clearable />
      </el-form-item>
      <el-form-item label="收货省份" prop="provinces">
        <el-select v-model="queryParams.receivingProvince" clearable size="small">
          <el-option
            v-for="item in provinceData"
            :key="item.name"
            :label="item.name"
            :value="item.id" />
        </el-select>
      </el-form-item>
<!--      <el-form-item label="订单渠道" prop="provinces">-->
<!--        <el-select v-model="queryParams.orderChannel" clearable @change="handleChange" size="small">-->
<!--          <el-option-->
<!--            v-for="item in orderChannelMap"-->
<!--            :key="item.value"-->
<!--            :label="item.label"-->
<!--            :value="item.value" />-->
<!--        </el-select>-->
<!--      </el-form-item>-->
      <el-form-item class="flex_one tr">
        <el-button type="primary" icon="el-icon-search" size="small" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="small" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :style="{ marginBottom: '10px' }">
      <el-col :span="12" :style="{ display: 'flex', alignItems: 'center', gap: '10px' }">
        <span>已选{{ids.length}}条</span>
        <el-button
          type="primary"
          icon="el-icon-printer"
          size="small"
          :disabled="!ids.length || !selectable"
          @click="handlePrint">打印</el-button>
      </el-col>
      <el-col :span="12" :style="{ display: 'flex', justifyContent: 'flex-end' }">
        <el-button type="primary" icon="el-icon-edit" size="small" @click="handleChangeSelect">批量选择</el-button>
      </el-col>
    </el-row>
    <el-table
      v-loading="loading"
      :data="orderList"
      :selectable="selectable"
      row-key="currentShippingId"
      @selection-change="handleSelectionChange"
      cell-class-name="my-cell">
      <el-table-column
        type="selection"
        width="55"
        align="center"
        v-if="selectable"
        :selectable="checkSelectable" />
      <el-table-column label="序号" type="index" :index="index => index + 1" />
      <el-table-column prop="orderId" label="订单ID" />
      <el-table-column prop="orderType" label="订单类型">
        <template slot-scope="scope">
          <div v-if="scope.row.orderType === 'PLAN'">计划订单</div>
          <div v-else>商品订单</div>
        </template>
      </el-table-column>
      <el-table-column label="下单日期" prop="createTime" width="200">
        <template slot-scope="scope">
          <div v-if="scope.row.placeOrderTime">{{parseTimeFormat(scope.row.placeOrderTime)}} 下单</div>
        </template>
      </el-table-column>
      <el-table-column prop="orderPhone" label="下单手机号" />
      <el-table-column prop="orderActualAmount" label="实付金额" />
      <el-table-column label="状态" prop="status" width="160">
        <template v-slot="scope">
          <el-tag :type="getOrderStatusTag(scope.row)">
            {{getOrderStatusText(scope.row)}}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" class-name="small-padding fixed-width" width="220" fixed="right" >
        <template slot-scope="scope">
          <div>
            <el-button
              size="mini"
              type="text"
              :disabled="scope.row.orderStatus !== 'PENDING_SHIPMENT'"
              @click="handleDelivery(scope.row)">发货</el-button>
            <el-button
              size="mini"
              type="text"
              @click="goDetail(scope.row)">查看</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <InBody v-show="total>0">
      <pagination
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList" />
    </InBody>
  </div>
</template>

<script>
import AddressSelector from "@/views/components/AddressSelector/index.vue";
import dateUtil from '@/utils/DateUtil';
import { mapGetters } from "vuex";
import { queryAreaData } from "@/api/activity";
import { queryOrderList, refundOrder } from "@/api/order";
import { mergePdfs } from '@/utils'
import { omit, omitBy } from 'lodash'
import moment from 'moment'
import { getExpressOrder, sendExpressOrder } from "@/api/logistics";

const OrderTypeMap = [
  {
    label: '全部订单',
    value: ''
  },
  {
    label: '计划订单',
    value: 'PLAN'
  },
  {
    label: '商品订单',
    value: 'PRODUCT'
  }
];
const OrderStatusMap = [
  {
    label: '待分享',
    value: 'PENDING'
  },
  {
    label: '待支付',
    value: 'PENDING_PAYMWENT'
  },
  {
    label: '待发货',
    value: 'PENDING_SHIPMENT'
  },
  {
    label: '待收货',
    value: 'PENDING_RECEIPT'
  },
  {
    label: '已完成',
    value: 'COMPLETED'
  },
  {
    label: '已取消',
    value: 'CANCELED'
  },
  {
    label: '已退款',
    value: 'REFUNDED'
  }
]

// 下单渠道
// const OrderChannelMap = {
//   0: '微信',
//   1: '淘宝',
//   2: '小红书'
// };

export default {
  name: "/order/list",
  computed:{ ...mapGetters(['userId']) },
  components: {
    AddressSelector
  },
  data() {
    return {
      // 遮罩层
      loading: false,
      // 订单状态字典
      orderStatusMap: OrderStatusMap,
      // 订单类型字典
      orderTypeMap: OrderTypeMap,
      // 下单渠道字典
      // orderChannelMap: Object.keys(OrderChannelMap).map(key => ({ value: key, label: OrderChannelMap[key] })),
      // 时间配置
      pickerOptions: {
        shortcuts: dateUtil.getTimeShort2()
      },
      provinceData: [],
      selectable: false,
      // 导出遮罩层
      // 选中数组
      ids: [],
      // 总条数
      total: 0,
      // 订单表表格数据
      orderList: [],
      // 弹出层标题
      title: "",
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderType: '',
        // orderChannel: null,
        orderStatus: '',
        Time: [],
        receivingProvince: '',
        orderPhone: '',
        startDateTime: '',
        endDateTime: ''
      }
    };
  },
  async created() {
    Promise.all([this.getList(), this.queryArea()]).catch()
  },
  methods: {
    parseTimeFormat (value) {
      return moment(value).format('YYYY-MM-DD HH:mm:ss')
    },
    // 有快递单号的才可以选
    checkSelectable(row) {
      if (!this.selectable) return false;
      const shipping = row.shippingPojos.find(v => v.id === row.currentShippingId)
      return !!shipping?.shippingWaybills?.length
    },
    // 打印面单
    async handlePrint() {
      if (!this.selectable) return;
      const { code: orderCode, data } = await getExpressOrder(this.ids)
      if (orderCode !== 200) return this.$message.error('面单生成失败')
      if (!data.success) return this.$message.error(data.errorMessage)
      const files = data?.obj?.files || []
      const pdfUrl = await mergePdfs(files);
      const { code } = await this.$print(pdfUrl)
      if (code !== 200) this.$message.error('打印失败')
    },
    handleChangeSelect() {
      this.selectable = !this.selectable
    },
    indexMethod(index) {
      return index + 1;
    },
    /** 查询订单表列表 */
    async getList() {
      this.loading = true
      if (this.queryParams.Time) {
        this.queryParams.startDateTime = this.queryParams.Time[0]
        this.queryParams.endDateTime = this.queryParams.Time[1]
      }
      let params = { ...omit(this.queryParams, 'Time') }
      const { code, rows, total } = await queryOrderList(omitBy(params, v => !v))
      this.loading = false
      if (code !== 200) return;
      this.orderList = rows
      this.total = +total
    },
    // 重置表单
    resetForm(key) {
      Object.assign(this.$data[key], this.$options.data()[key]);
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.currentShippingId).filter(v => v)
    },

    // 时间搜索条件change方法
    handleChange(value) {
      if (!value) {
        this.queryParams.startDateTime = null;
        this.queryParams.endDateTime = null;
      }
    },
    getOrderStatusTag(row) {
      const statusMap = {
        'REFUNDED': 'info',
        'CANCELED': 'info',
        'CANCEL_BEFORE_SHIPMENT': 'info',
        'CANCELED_REFUNDED': 'info',
        'PENDING_RECEIPT': 'primary',
        'COMPLETED': 'success',
        'PENDING_SHIPMENT': 'warning',
        'PENDING_PAYMWENT': 'warning',
        'UNFINISHED_PAYMENT_CANCEL': 'warning',
        'GROUP_ORDER_FAIL_CANCLE': 'warning',
        'PENDING': 'warning',
        'ALREADY_SHARED': 'warning'
      }
      if (statusMap[row.orderStatus]) return statusMap[row.orderStatus]
      if (row.shareStatus === 'PENDING') return statusMap['PENDING']
      return ''
    },
    getOrderStatusText(row) {
      const statusMap = {
        'REFUNDED': '已退款',
        'CANCELED': '已取消',
        'PENDING_RECEIPT': '待收货',
        'COMPLETED': '已完成',
        'PENDING_SHIPMENT': '待发货',
        'PENDING_PAYMWENT': '待支付',
        'UNFINISHED_PAYMENT_CANCEL': '未完成支付取消',
        'CANCEL_BEFORE_SHIPMENT': '发货前取消',
        'GROUP_ORDER_FAIL_CANCLE': '拼单失败取消',
        'CANCELED_REFUNDED': '已取消,退款成功',
        'PENDING': '待分享',
        'ALREADY_SHARED': '已分享'
      }
      if (statusMap[row.orderStatus]) return statusMap[row.orderStatus]
      if (row.shareStatus === 'PENDING') return '待分享'
      return '未知状态'
    },
    // 查看详情
    goDetail(row) {
      this.$router.push({ path: '/order/detail', query: { id: row.orderId } })
    },
    // 发货
    handleDelivery(row) {
      this.$confirm('确定发货吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { code, msg } = await sendExpressOrder({ shippingId: row.currentShippingId })
        if (code !== 200) return this.$message.error(msg)
        return this.getList()
      }).catch()
    },
    // 获取省份
    async queryArea() {
      const { code, data } = await queryAreaData()
      if (code !== 200) return;
      this.provinceData = data
    },
  }
};
</script>
<style lang="scss">
.product-container {
  display: flex;
  flex-direction: row;
  align-items: center;
  width: 340px;

  .product-item {
    margin: auto;
    width: 290px;

    .sp-data {
      font-size: 13px;
    }

    .quantity {
      font-weight: bold;
      font-size: 13px;
    }
  }
}

.note-title {
  font-weight: bold;
}

.el-table .my-cell {
  vertical-align: top
}

.el-link.el-link--default {
  color: #409eff;
}

.el-select {
  width: 100%;
}
</style>
